import { Tabs } from 'antd';
import React, { Component } from 'react';
import ProductList from './ProductList';

const { TabPane } = Tabs;

export default class ProductManagement extends Component {
	constructor(props) {
		super(props);
		this.newTabIndex = 0;
		const panes = [
			{
				title: '商品列表',
				content: <ProductList handleClick={this.add} />,
				key: '1',
				closable: false
			},
			{
				title: '新建商品',
				content: <div>我是新建商品的组件</div>,
				key: '2',
				closable: false
			}
		];
		this.state = {
			// activeKey为当前展示页面对应的key
			activeKey: panes[0].key,
			panes
		};
	}
	// 点击的tabs发生变化，就将state中的activeKey变为当前的activeKey，state一变就会重新渲染，tabs就可以接到当前应该指向的页面
	onChange = (activeKey) => {
		this.setState({ activeKey });
	};
	// 在这里应该进行一下判断，如果activeKey是1则重新加载一下数据库数据

	onEdit = (targetKey, action) => {
		this[action](targetKey);
	};

	// 用于详情页添加tab
	add = (record) => {
		const { panes } = this.state;
		const activeKey = `newTab${this.newTabIndex++}`;
		panes.push({
			title: '订单详情',
			// content调用一个详情组件
			content: <div>我是详情</div>,
			key: activeKey,
			closable: true
		});
		this.setState({ panes, activeKey });
	};

	remove = (targetKey) => {
		let { activeKey } = this.state;
		let lastIndex;
		this.state.panes.forEach((pane, i) => {
			if (pane.key === targetKey) {
				lastIndex = i - 1;
			}
		});
		const panes = this.state.panes.filter((pane) => pane.key !== targetKey);
		if (panes.length && activeKey === targetKey) {
			if (lastIndex >= 0) {
				activeKey = panes[lastIndex].key;
			} else {
				activeKey = panes[0].key;
			}
		}
		this.setState({ panes, activeKey });
	};

	render() {
		return (
			// 整个是一个div，div里有一个tab组件，通过遍历state中的panes来自动生成pane，每一个都返回一个tabpane组件
			<div>
				<Tabs
					hideAdd
					onChange={this.onChange}
					activeKey={this.state.activeKey}
					type="editable-card"
					onEdit={this.onEdit}
				>
					{this.state.panes.map((pane) => (
						<TabPane tab={pane.title} key={pane.key} closable={pane.closable}>
							{pane.content}
						</TabPane>
					))}
				</Tabs>
			</div>
		);
	}
}
